from flask import Blueprint, request, jsonify
import random
import string
from datetime import datetime, timedelta
from .share import shared_vars

worker_nodes_bp = Blueprint('worker_nodes', __name__)

def random_string(length=10):
    return ''.join(random.choices(string.ascii_letters, k=length))

def random_time():
    now = datetime.now()
    delta = timedelta(days=random.randint(0, 30), 
                      hours=random.randint(0, 23),
                      minutes=random.randint(0, 59))
    return (now - delta).strftime('%Y-%m-%d %H:%M:%S')

@worker_nodes_bp.route('/', methods=['GET'])
def get_worker_nodes():
    page_id = request.args.get('page_id', 1)
    
    nodes = []
    nodes = [node for node in shared_vars['workers']]
    for _ in range(3):
        nodes.append({
            'worker_id'        : random_string(),
            'os_version'       : random.choice(['windows', 'linux']),
            'boot_time'        : random_time(),
            'available_cpu'    : random.randint(10, 50),
            'available_memory' : random.randint(100, 900),
            'running_tasks'    : random.randint(0, 10),
            'version'          : f"{random.randint(1, 5)}.{random.randint(0, 9)}.{random.randint(0, 9)}",
            'is_enabled'       : random.choice([0, 1])
        })
    
    return jsonify({'nodes': nodes})

@worker_nodes_bp.route('/enable', methods=['POST'])
def enable_worker_node():
    data = request.get_json()
    worker_id = data.get('worker_id')
    is_enable = data.get('is_enable')
    return jsonify({'success': True, 'message': f'Worker {worker_id} {"enabled" if is_enable else "disabled"}'})

@worker_nodes_bp.route('/register-url', methods=['GET'])
def get_register_url():
    return jsonify({
        'url': ''.join(random.choices(string.ascii_letters + string.digits, k=30)),
        'timeout': int((datetime.now() + timedelta(minutes=5)).timestamp())
    })
